<template>
  <el-dialog
    title="从其他任务复制考核方案"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="copy-from-other-content">
      <!-- 目标任务信息 -->
      <el-card v-if="targetMission" class="target-card" style="margin-bottom: 20px;">
        <template #header>
          <div class="card-header">
            <span>复制到以下任务</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程名称">{{ targetMission.courseName }}</el-descriptions-item>
          <el-descriptions-item label="学期">{{ targetMission.termName }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 过滤条件 -->
      <el-form :inline="true" label-width="120px" style="margin-bottom: 20px;">
        <el-form-item label="选择学期">
          <el-select 
            v-model="selectedTermId" 
            placeholder="请选择学期" 
            style="width: 200px;"
            @change="handleTermChange"
          >
            <el-option 
              v-for="term in terms" 
              :key="term.id" 
              :label="term.name" 
              :value="term.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input
            v-model="courseNameFilter"
            placeholder="输入课程名称进行筛选"
            style="width: 250px;"
            clearable
            @input="handleCourseNameFilterChange"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 源任务选择 -->
      <el-card>
        <template #header>
          <div class="card-header">
            <span>选择要复制的考核方案</span>
          </div>
        </template>

        <div v-loading="loading">
          <el-table
            :data="availableMissions"
            style="width: 100%"
            @row-click="handleMissionSelect"
            highlight-current-row
            v-model:current-row="selectedMission"
            height="350"
          >
            <el-table-column prop="courseName" label="课程名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="termName" label="学期" width="120" />
            <el-table-column label="考核组成详情" min-width="350">
              <template #default="scope">
                <div v-if="scope.row.examParts && scope.row.examParts.length > 0" class="exam-parts-preview">
                  <div class="exam-parts-header">
                    <span class="parts-count">共{{ scope.row.examParts.length }}个部分</span>
                    <el-tag type="success" size="small" effect="plain">总计100%</el-tag>
                  </div>
                  <div class="exam-parts-list">
                    <div 
                      v-for="(part, index) in scope.row.examParts" 
                      :key="index"
                      class="exam-part-item"
                    >
                      <span class="part-name">{{ part.name }}</span>
                      <span class="part-proportion">{{ part.proportion }}%</span>
                      <el-tag 
                        v-if="part.examPartType === 'FORMATIVE'" 
                        type="success" 
                        size="small" 
                        effect="plain"
                      >
                        形成性
                      </el-tag>
                      <el-tag 
                        v-else-if="part.examPartType === 'FINAL'" 
                        type="warning" 
                        size="small" 
                        effect="plain"
                      >
                        终结性
                      </el-tag>
                      <el-tag 
                        v-else 
                        type="info" 
                        size="small" 
                        effect="plain"
                      >
                        其它
                      </el-tag>
                    </div>
                  </div>
                </div>
                <span v-else class="text-muted">
                  <el-icon><WarningFilled /></el-icon>
                  无有效考核组成
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small" 
                  :disabled="selectedMission?.id === scope.row.id"
                  @click.stop="handleMissionSelect(scope.row)"
                >
                  {{ selectedMission?.id === scope.row.id ? '已选择' : '选择' }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-empty 
            v-if="!loading && availableMissions.length === 0" 
            description="当前条件下暂无可复制的考核方案"
            :image-size="100"
          >
            <template #description>
              <div class="empty-description">
                <p>当前条件下暂无可复制的考核方案</p>
                <p class="empty-tip">请尝试：</p>
                <ul class="empty-tips">
                  <li>选择其他学期</li>
                  <li>清除课程名称筛选条件</li>
                  <li>确保源任务已设置完整的考核组成（总比例为100%）</li>
                </ul>
              </div>
            </template>
          </el-empty>
        </div>
      </el-card>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleCopy"
        :disabled="!selectedMission"
        :loading="copying"
      >
        复制考核方案
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, WarningFilled } from '@element-plus/icons-vue'
import { termApi } from '@/api/base-data'
import { teachingMissionApi } from '@/api/teaching-mission'
import { courseExamPartApi } from '@/api/course-exam-part'

const props = defineProps({
  visible: { type: Boolean, default: false },
  targetMission: { type: Object, default: () => null }
})

const emit = defineEmits(['update:visible', 'copy-success'])

const loading = ref(false)
const copying = ref(false)
const terms = ref([])
const selectedTermId = ref(null)
const allMissions = ref([])
const selectedMission = ref(null)
const courseNameFilter = ref('')

// 过滤后的可用任务列表
const availableMissions = computed(() => {
  if (!courseNameFilter.value) {
    return allMissions.value
  }
  
  const filterText = courseNameFilter.value.toLowerCase()
  return allMissions.value.filter(mission => 
    mission.courseName?.toLowerCase().includes(filterText)
  )
})

const fetchTerms = async () => {
  try {
    const response = await termApi.getAllTerms()
    terms.value = response || []
    const currentTerm = terms.value.find(term => term.isCurrent)
    if (currentTerm) {
      selectedTermId.value = currentTerm.id
      await handleTermChange()
    }
  } catch (error) {
    console.error('获取学期列表失败:', error)
    ElMessage.error('获取学期列表失败')
  }
}

const handleTermChange = async () => {
  if (!selectedTermId.value) {
    availableMissions.value = []
    return
  }
  await fetchAvailableMissions()
}

const fetchAvailableMissions = async () => {
  if (!selectedTermId.value) return
  loading.value = true
  try {
    const response = await teachingMissionApi.getTeachingMissionsByTerm(selectedTermId.value)
    const missions = response || []
    
    const missionsWithExamParts = await Promise.all(
      missions.map(async (mission) => {
        try {
          const examPartsResponse = await courseExamPartApi.getExamPartsByTeachingMission(mission.id)
          const examParts = examPartsResponse || []
          const totalProportion = examParts.reduce((sum, part) => sum + (part.proportion || 0), 0)
          
          if (totalProportion === 100 && examParts.length > 0 && mission.id !== props.targetMission?.id) {
            return { ...mission, examParts }
          }
          return null
        } catch (error) {
          return null
        }
      })
    )
    
    allMissions.value = missionsWithExamParts.filter(mission => mission !== null)
  } catch (error) {
    console.error('获取教学任务列表失败:', error)
    ElMessage.error('获取教学任务列表失败')
  } finally {
    loading.value = false
  }
}

const handleCourseNameFilterChange = () => {
  // 清除当前选择的任务，因为过滤后原选择可能不在列表中
  if (selectedMission.value && !availableMissions.value.includes(selectedMission.value)) {
    selectedMission.value = null
  }
}

const handleMissionSelect = (row) => {
  selectedMission.value = row
}

const handleCopy = async () => {
  if (!selectedMission.value) {
    ElMessage.warning('请选择要复制的任务')
    return
  }
  
  copying.value = true
  try {
    await courseExamPartApi.copyExamPartsToOtherMissions(
      selectedMission.value.id,
      [props.targetMission.id]
    )
    
    ElMessage.success('复制考核方案成功')
    emit('copy-success')
    handleClose()
  } catch (error) {
    console.error('复制考核方案失败:', error)
    ElMessage.error('复制考核方案失败')
  } finally {
    copying.value = false
  }
}

const handleClose = () => {
  selectedMission.value = null
  courseNameFilter.value = ''
  emit('update:visible', false)
}

watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    fetchTerms()
  }
})
</script>

<style scoped>
.copy-from-other-content {
  max-height: 600px;
  overflow-y: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.exam-parts-preview {
  padding: 8px 0;
}

.exam-parts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #ebeef5;
}

.parts-count {
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.exam-parts-list {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.exam-part-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background-color: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
}

.part-name {
  flex: 1;
  color: #303133;
  font-weight: 500;
}

.part-proportion {
  color: #409eff;
  font-weight: 600;
  min-width: 40px;
  text-align: right;
}

.text-muted {
  color: #c0c4cc;
  display: flex;
  align-items: center;
  gap: 4px;
  font-style: italic;
}

.target-card {
  background-color: #f8f9fa;
}

.empty-description {
  text-align: center;
  color: #909399;
}

.empty-tip {
  margin: 8px 0 4px 0;
  font-size: 14px;
  color: #606266;
}

.empty-tips {
  text-align: left;
  margin: 0;
  padding-left: 20px;
  font-size: 13px;
  color: #909399;
}

.empty-tips li {
  margin: 4px 0;
}
</style>
